package com.sls.mall.product.app;

import org.redisson.api.RCountDownLatch;
import org.redisson.api.RLock;
import org.redisson.api.RReadWriteLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.UUID;

@Controller
public class HelloController {

    @Autowired
    RedissonClient redisson;

    @Autowired
    StringRedisTemplate redisTemplate;

    @ResponseBody
    @GetMapping("/hello")
    public String hello(){
        //1.获取一把锁，只要名字一样就是同一把锁
        RLock lock = redisson.getLock("my-lock");
        //2.枷锁
        lock.lock();//阻塞式等待
        try{
            System.out.println("加锁成功，执行业务。。。"+Thread.currentThread().getId());
            Thread.sleep(10000);
        } catch (Exception e){

        } finally {
            //3.解锁
            System.out.println("释放锁。。。"+Thread.currentThread().getId());
            lock.unlock();
        }

        return "hello";
    }

    @ResponseBody
    @GetMapping("/write")
    public String write(){
        RReadWriteLock lock = redisson.getReadWriteLock("rw-lock");
        RLock rLock = lock.writeLock();
        String s = "";
        try {
            rLock.lock();//改数据加写锁，读数据加读锁
            System.out.println("写锁加锁成功。。。");
            Thread.sleep(30000);
            s = UUID.randomUUID().toString();
            redisTemplate.opsForValue().set("writeValue", s);
        } catch (Exception e){

        } finally {
            rLock.unlock();
        }
        return s;
    }

    @ResponseBody
    @GetMapping("/read")
    public String read(){
        RReadWriteLock lock = redisson.getReadWriteLock("rw-lock");
        RLock rLock = lock.readLock();

        rLock.lock();
        System.out.println("写锁加锁成功。。。");
        String s = redisTemplate.opsForValue().get("writeValue");
        return s;
    }

    /**
     * 闭锁
     * @return
     * @throws InterruptedException
     */
    @ResponseBody
    @GetMapping("/lockDoor")
    public String lockDoor() throws InterruptedException {
        RCountDownLatch door = redisson.getCountDownLatch("door");
        door.trySetCount(5);
        door.await();
        return "放假了。。。";
    }

    @ResponseBody
    @GetMapping("/gogogo/{id}")
    public String gogo(@PathVariable("id") Long id) throws InterruptedException {
        RCountDownLatch door = redisson.getCountDownLatch("door");
        door.countDown();
        return id+"班的人都走了。。。";
    }

}
